# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

import urllib
from .saltapi import salt
from .models import Minion, Process, Project, SysProc
from saltops.forms import PaginationForm

def factory(procs, projects, sysprocs):
    ## 遍历Process列表, 标记其中的'业务进程'
    ## category: 0(未定义), 1(系统进程), 2(业务进程)

    for proc in procs:
        proc['category'] = 0
        for proj in projects:
            if proc['psStr'].find(proj['psStr']) != -1:
                proc['category'] = 2
                break
        if proc['category'] != 0: continue
        for sysproc in sysprocs:
            if proc['psStr'].find(sysproc['psStr']) != -1:
                proc['category'] = 1
                break
    return procs

def query(req):
    form = PaginationForm(req.GET)
    if not form.is_valid(): pass
    params = form.getPaginationParams()
    limit   = params['limit']
    offset  = params['offset']
    sort    = params['sort']
    order   = params['order']

    minionId = req.GET['minionId']
    minion = Minion.objects.get(key = minionId)

    projects = Project.objects.filter(minion = minion)
    projects = [proj.parse() for proj in projects]

    sysprocs = SysProc.objects.all()
    sysprocs = [sysproc.parse() for sysproc in sysprocs]

    procs = Process.objects.filter(minion = minion)
    count = procs.count()
    procs = procs[offset: offset + limit]
    procs = [proc.parse() for proc in procs]

    result = {
        'rows': factory(procs, projects, sysprocs),
        'total': count,
    }
    return JsonResponse(result)
